package login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-10-16
 * Time: 19:49
 */
//用来处理登录请求
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        //读取请求中的参数, 判断当前的用户身份信息是否正确
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || username.equals("") || password == null || password.equals("")){
            //这几个情况都表示前端发来的参数不完整, 直接返回到登录界面
            resp.getWriter().write("用户名或密码不完整! 登录失败!");
            return;
        }
        //验证用户名密码是否正确
        if(!username.equals("cxz") || !password.equals("123456")) {
            resp.getWriter().write("用户名或密码错误! 登录失败!");
            return;
        }
        //登录成功则创建一个会话(session), 把用户信息填写到session中
        HttpSession session = req.getSession(true);
        session.setAttribute("username", "cxz");
        Integer visitCount = (Integer)session.getAttribute("visitCount");
        if(visitCount == null){
            session.setAttribute("visitCount", 0);
        }
        //让页面跳转到登录页面, 这里的重定向跳转是一个get请求
        resp.sendRedirect("index");
    }
}
